<?php
/**
 * erp日销售额报表 (erp)
 */
namespace App\Logic\SalesReport;

use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlat;
use App\Models\SalesAmazon\SalesAmountDay;
use App\Models\SalesReport\DailyAmount;
use Illuminate\Support\Facades\DB;

class DailySaleAmount
{

    //销量金额(日)统计报表(erp) (默认，倒推7天销售额)
    public static function init($days = 7){

        $i = 1;
        while(true) {
            if ($i > $days) break;
            $date = date('Y-m-d',strtotime("-{$i} days"));
            $day = date('Ymd',strtotime("-{$i} days"));

            try{
                DB::beginTransaction();
                DailyAmount::query()->where('report_date',$date)->update(['amount' => 0]);

                $areaArr = [];
                SalesAmountDay::query()
                    ->where('day',$day)
                    ->select('day','country_id','account_id','plat_id',DB::raw('sum(amount * rate_odds) as amount'))
                    ->groupBy('day','country_id','account_id','plat_id')
                    ->chunk(500, function ($items) use(&$areaArr,$date){
                        foreach ($items as $item){
                            $countryId = $item->country_id;
                            if(!array_key_exists($countryId,$areaArr)){
                                $areaArr[$countryId] = SysICountry::getAreaIdByCountryId($countryId);
                            }
                            $areaId = $areaArr[$countryId];

                            DailyAmount::query()->updateOrCreate([
                                'report_date' => $date,
                                'country_id'  => $countryId,
                                'account_id'  => $item->account_id,
                                'plat_id'     => $item->plat_id
                            ],[
                                'area_id' => $areaId,
                                'amount'  => $item->amount
                            ]);
                        }
                    });

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }

            echo $date.PHP_EOL;
            $i++;
            sleep(5);
        }
    }

    /**
     * 补平台数据
     * @param $startDate
     * @param $endDate
     * @return false
     */
    public static function initBack($startDate,$endDate){

        $shopifyPlat = SysPlat::PLAT_SHOPIFY;

        $startDates = $startDate == 'null' ? date('Y-m-d', strtotime("-1 days")) : $startDate; //开始时间
        $endDates = $endDate == 'null' ? date('Y-m-d', strtotime("-1 days")) : $endDate; //结束时间
        if (!strtotime($startDates) || !strtotime($endDates)) return false;

        $bof = strtotime($startDates); //开始
        $eof = strtotime($endDates); //结束
        while(true) {
            if ($bof > $eof) break;
            $time = $bof;
            $date = date('Y-m-d',$time);
            $day = date('Ymd',$time);

            try{
                DB::beginTransaction();
                DailyAmount::query()->where('plat_id',$shopifyPlat)->where('report_date',$date)->update(['amount' => 0]);

                $areaArr = [];
                SalesAmountDay::query()
                    ->where('plat_id',$shopifyPlat)
                    ->where('day',$day)
                    ->select('day','country_id','account_id','plat_id',DB::raw('sum(amount * rate_odds) as amount'))
                    ->groupBy('day','country_id','account_id','plat_id')
                    ->chunk(500, function ($items) use(&$areaArr,$date){
                        foreach ($items as $item){
                            $countryId = $item->country_id;
                            if(!array_key_exists($countryId,$areaArr)){
                                $areaArr[$countryId] = SysICountry::getAreaIdByCountryId($countryId);
                            }
                            $areaId = $areaArr[$countryId];

                            DailyAmount::query()->updateOrCreate([
                                'report_date' => $date,
                                'account_id'  => $item->account_id,
                                'country_id'  => $countryId,
                                'plat_id'     => $item->plat_id,
                            ],[
                                'area_id' => $areaId,
                                'amount'  => $item->amount
                            ]);
                        }
                    });

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
            }

            echo $day.PHP_EOL;
            $bof += 60*60*24;
            sleep(2);
        }
    }

}
